﻿using MarkdownWeb.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MarkdownWeb.Controllers
{
    public class CreateController : Controller
    {
        // GET: Create
        public ActionResult Index(string title = null)
        {
            if (title != null)
                ViewData["title"] = title;
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public JsonResult New(FormCollection form)
        {
            var data = form["data"];
            var title = form["title"];
            JsonResult ret = new JsonResult();
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<WikiContentContext>());
            var context = new WikiContentContext();
            if(context.Wikis.FirstOrDefault(w=>w.Title == title) != null)
            {
                ret.Data = new { result = "已经存在此标题页面" };
                return ret;
            }
            var content = new WikiContent();            
            content.CreateTime = DateTime.Now;
            content.Creater = Session["name"] as string;
            content.Content = data;
            content.Title = title;
            content.LastEditTime = content.CreateTime;
            context.Wikis.Add(content);
            context.SaveChanges();
            
            ret.Data = new { result = "ok" ,title= form["title"] };
            return ret;
        }
    }
}